<template>
  <div id="copy">
    <el-dialog
      :title="this.dateRange + '考核结果'"
      :visible.sync="dialogVisible"
      top="5vh"
      width="95%"
      center
    >
      <el-table
        v-loading="loading"
        :data="data"
        style="width: 100%"
        :max-height="maxTableH"
        size="mini"
        border
        :default-sort = "{prop: 'total', order: 'descending'}"
        @sort-change="handleSort"
      >
        <el-table-column prop="organizationName" label="机构名称"  align="center"></el-table-column>

        <template v-for="item in tableCols">
          <el-table-column
            align="center"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
          >
            <template v-if="item.children">
                <template v-for="(child) in item.children">
                      <el-table-column
                       align="center"
                      :key="child.prop"
                      :label="child.label"
                      :prop="child.prop"
                      sortable="custom"
                      >
                        <template slot-scope="{row}">
                        <p class="text-center p-tb-10">{{toFixed(row[child.prop])}}</p>
                        </template>
                      </el-table-column>
                </template>
            </template>
            <template slot-scope="{row}">
              <p class="text-center p-tb-10">{{toFixed(row[item.prop])}}</p>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" size="small" @click="copyValue">复 制 内 容</el-button> -->
         <el-button type="primary" v-if="showDetailStatus" @click="handleDetailResult()" size="small">查 看 明 细</el-button>
        <el-button type="primary" @click="dialogVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="this.dateRange + '得分明细表'"
      :visible.sync="detaildialogVisible"
      top="1vh"
      width="75%"
      center
    >
      <TableComp :col="detailcol" :data="detaildata"></TableComp>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="copyValue">下 载</el-button>
        <el-button type="primary" @click="detaildialogVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTaskResult, getModel, getTaskDetailResult } from '@/api/api.js'
import {downloadExcel} from '@/components/excel/downloadExcel.js'
export default {
  components: {
    TableComp: () => import('@/components/table/MyTable.vue')
  },
  props: {
    taskId: String,
    uuid: String,
    dateRange: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      dialogVisible: false,
      detaildialogVisible: false,
      loading: false,
      data: [],
      tableCols: [],
      showResultCols: [],
      resultPermission: null,
      isDetailed: null,
      detailcol: [],
      detaildata: [],
      showDetailStatus: false,
      totalScoreStatus: false
    }
  },
  computed: {
    maxTableH () {
      return document.body.clientHeight * 0.8 - 100
    }
  },
  mounted () {
    this.resultPermission = this.$store.state.user.resultPermission
    // console.log(this.resultPermission)
    // this.showResultCols = this.totalResultCols.filter(col => {
    //   let flag = true
    //   if (!col.properties) {
    //     flag =
    //       this.resultPermission === 'ALL'
    //         ? true
    //         : this.resultPermission === col.permission
    //     return flag
    //   }
    //   const properties = col.properties
    //   const filteredPros = properties.filter(pro => {
    //     return (
    //       this.resultPermission === 'ALL' ||
    //       this.resultPermission === pro.permission
    //     )
    //   })
    //   if (!filteredPros.length) {
    //     flag = false
    //   }
    //   return flag
    // })
  },
  methods: {
    init () {
       /* 判断calculate_type是否为1 */
        getModel(this.uuid).then(res => {
          if (res.calculatetype === 1) {
              this.isDetailed = true
          } else {
              this.isDetailed = false
          }
          this.showDetailStatus = (res.showDetailStatus === 'active')
          this.totalScoreStatus = (res.totalScoreStatus === 'active')
      })
      /* 初始化表头、表格数据 */
      this.detailcol = []
      this.detaildata = []
      this.data = []
      this.loading = true
      getTaskResult({ taskId: this.taskId, detailActive: false })
        .then(res => {
          if (res instanceof Array) {
            if(this.$store.state.user.taskRole === 'organization') {
              const sumTemp = {}
              const sumItem = {}
              Object.assign(sumItem, res[0])
              for(let key in res[0]) {
                if (res[0][key] instanceof Array) {
                  this.$set(sumItem, key, [])
                  res[0][key].forEach(resItem => {
                    const nodeItem = {}
                    Object.assign(nodeItem, resItem)
                    sumItem[key].push(nodeItem)
                  })
                } else {
                  this.$set(sumItem, key, res[0][key])
                }
              }
              sumItem.organizationName = '合计'
              sumItem.childrenNodes.forEach(node => {
                this.$set(sumTemp, node.name, 0)
              })
              res.forEach(item => {
                if (item.childrenNodes)
                item.childrenNodes.forEach(nodeItem => {
                  sumTemp[nodeItem.name] += nodeItem.score
                })
              })
              sumItem.childrenNodes.forEach(node => {
                node.score = sumTemp[node.name]
              })
              res.push(sumItem)
            }
            const cols = res[0].childrenNodes
            this.tableCols = cols.map((col, index) => {
                  if (col.childrenNodes && col.childrenNodes.length!==0) {
                       const children = []
                       col.childrenNodes.map((child, index) => {
                            children.push({ label: child.name, prop: child.name })
                       })
                      children.push({ label: col.name, prop: col.name })
                      return {
                        label: col.name,
                        prop: col.name,
                        children: children
                      }
                  } else {
                    return {
                        label: col.name,
                        prop: col.name
                    }
                  }
            })
            if (this.totalScoreStatus) {
              this.tableCols.push({ label: '总分', prop: 'total' })
            }
            res = res.map(item => {
              let temp = item
              const nodes = item.childrenNodes
              if (nodes)
              nodes.forEach(n => {
                  if (n.childrenNodes) {
                    const nodeObj = {}
                    nodeObj[n.name] = n.score
                    temp = Object.assign({}, temp, nodeObj)

                    n.childrenNodes.forEach(item => {
                      const nodeObj = {}
                      nodeObj[item.name] = item.score
                      temp = Object.assign({}, temp, nodeObj)
                    })
                  } else {
                    const nodeObj = {}
                    nodeObj[n.name] = n.score
                    temp = Object.assign({}, temp, nodeObj)
                  }
              })
              return temp
            })
            res.sort(function (a, b) {
              return a.total < b.total ? 1 : a.total > b.total ? -1 : 0
            })
            this.data = res
          } else {
              this.data = []
          }
          this.dialogVisible = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    /* 查看得分明细 */
    handleDetailResult () {
        this.dialogVisible = false
        this.detailcol.push({ label: '机构名称', prop: '机构名称', fixed: true })
        getTaskDetailResult({ taskId: this.taskId }).then(res => {
            if (res instanceof Array) {
                if (res && res.length) {
                  /* 组装表头数据 */
                  const firstcols = res[0].childrenNodes
                     firstcols.forEach(item => {
                       const obj = {}
                       obj.label = item.name
                       obj.children = []
                       if (item.childrenNodes) {
                         item.childrenNodes.forEach(secondcols => {
                           obj.children.push({ label: secondcols.name, prop: secondcols.name })
                         })
                       }
                       if (this.totalScoreStatus) {
                         obj.children.push({
                           label: item.name + '总分',
                           prop: item.name + '总分'
                         })
                       }
                       this.detailcol.push(obj)
                     })
                  if (this.totalScoreStatus) {
                    this.detailcol.push({
                      label: '总分',
                      prop: '总分'
                    })
                  }
                  /* 组装表格数据 */
                  res.forEach(item => {
                      const obj = {}
                      obj['机构名称'] = item.organizationName
                      item.childrenNodes.forEach(child => {
                          obj[child.name + '总分'] = child.score
                          child.childrenNodes.forEach(childs => {
                                   obj[childs.name] = childs.score
                          })
                      })
                      obj['总分'] = item.total
                      this.detaildata.push(obj)
                  })
                }
            } else {
                      this.detaildata = []
            }
            this.detaildialogVisible = true
        })
        .finally(() => {
        })
    },
    handleSort (data) {
      const order = data.order
      const prop = data.prop
      const lessThanSign = order === 'descending' ? 1 : -1
      const moreThanSign = order === 'descending' ? -1 : 1
      this.data.sort(function (a, b) {
        return a[prop] < b[prop] ? lessThanSign : a[prop] > b[prop] ? moreThanSign : 0
      })
    },
    toFixed (value) {
      if (parseFloat(value).toString() === 'NaN') {
        return 0
      }
      return Math.round(value * 100) / 100
    },
    copyValue () {
      let head = []
      /*二级表头*/
      let headData = []
      /*一级表头*/
      let headFather = []
      /*数据*/
      let data = []
      head.unshift('机构名称')
      if(this.detailcol) {
        for (let i = 0; i < this.detailcol.length; i++) {
          if(this.detailcol[i].children){
            if(headFather.length!==0){
              var obj = {label:this.detailcol[i].label,length:this.detailcol[i].children.length+headFather[headFather.length-1].length}
            }else{
              var obj = {label:this.detailcol[i].label,length:this.detailcol[i].children.length}
            }
            headFather.push(obj)
            var array = this.detailcol[i].children
            array.forEach(element => {
              head.push(element.label)
              headData.push(element.label)
            })
          }
        }
      }
      if (this.totalScoreStatus) {
        head.push('总分')
      }
      this.detaildata.forEach((item,index)=>{
        var newObj = [];
        for (var i = 0, len = head.length; i < len; i++) {
          newObj.push(item[head[i]])
        }
        data.push(newObj)
      })
      downloadExcel(headFather,headData,data,this.dateRange + '得分明细表')
    }
  }
}
</script>

<style lang="scss" scoped>
.f-b {
  font-weight: bold;
}
.p-b-10 {
  padding-bottom: 10px;
}
.flex-wrap {
  display: flex;
  // justify-content: space-between;
  flex-wrap: wrap;

  .th-tag {
    padding: 2px 4px;
    line-height: 16px;
    font-size: 10px;
    border-width: 1px;
    border-style: solid;
    background-color: #ecf5ff;
    border-color: #d9ecff;
    border-radius: 2px;
    color: #409eff;
    &:not(:last-of-type) {
      margin-right: 5px;
    }
    &.success {
      color: #67c23a;
      border-color: #e1f3d8;
      background-color: #f0f9eb;
    }
    &.danger {
      color: #f56c6c;
      border-color: #fde2e2;
      background-color: #fef0f0;
    }
    &.warning {
      color: #e6a23c;
      border-color: #faecd8;
      background-color: #fdf6ec;
    }
  }
}
.m-b-4 {
  margin-bottom: 4px;
}
</style>
